class Snake
{
    constructor(el)
    {
        this.el = el
        this.length = 20
        this.snakeObj = [
            { x: 3, y :2, color:'red', ele:null},  //蛇头
            { x: 2, y :2, color:'blue', ele:null}, // 蛇的身体
            { x: 1, y :2, color:'blue', ele:null}  // 蛇的身体
          ]
        // 方向
        this.direction = 'right'
    }

    remove () 
    {
        //父.removeChild(子)
        for (let i = 0; i<this.snakeObj.length; i++) {
            if (this.snakeObj[i].ele) {
                this.el.removeChild(this.snakeObj[i].ele)
            }
        }
    }

    create () 
    {
        this.remove()
        for (let i = 0; i<this.snakeObj.length; i++) {
            //创造一个snake标签
            let divObj = document.createElement('div')
            divObj.style.width = this.length + 'px'
            divObj.style.height = this.length + 'px'
            divObj.style.position = 'absolute'
            divObj.style.background = this.snakeObj[i].color
            divObj.style.left = this.snakeObj[i].x * this.length + 'px'
            divObj.style.top = this.snakeObj[i].y * this.length + 'px'
            //单独保存蛇节对象
            this.snakeObj[i].ele = divObj
            //追加到页面中
            this.el.appendChild(divObj)
        }
    }

    move () {
        // for (let i = 0;i < this.snakeObj.length;i ++) {
        //     this.snakeObj[i].x += 1
        // }
        for (let i = this.snakeObj.length - 1;i > 0;i--) {
            this.snakeObj[i].x = this.snakeObj[i-1].x
            this.snakeObj[i].y = this.snakeObj[i-1].y
        }
        switch (this.direction) {
            case 'top':
                this.snakeObj[0].y -= 1
                break;
            case 'bottom':
                this.snakeObj[0].y += 1
                break;
            case 'left':
                this.snakeObj[0].x -= 1
                break;
            case 'right':
                this.snakeObj[0].x += 1
                break;
        }
        //重新创建
        this.create()
    }
}